#include "EchoServer.h"
#include <iostream>
#include <unistd.h>
#include <sys/syscall.h>
#include "Log.h"

EchoServer::EchoServer(const char *ip, uint16_t port,int io_thread_num,int work_thread_num) : m_tcpserver(ip, port,io_thread_num),m_threadpool(work_thread_num,"WORKS")
{
    m_tcpserver.set_new_connection_callback(std::bind(&EchoServer::handle_new_connection,this,std::placeholders::_1));
    m_tcpserver.set_close_connection_callback(std::bind(&EchoServer::handle_close_connection,this,std::placeholders::_1));
    m_tcpserver.set_error_connection_callback(std::bind(&EchoServer::handle_error_connection,this,std::placeholders::_1));
    m_tcpserver.set_on_message_callback(std::bind(&EchoServer::handle_on_message,this,std::placeholders::_1,std::placeholders::_2));
    m_tcpserver.set_send_complete_callback(std::bind(&EchoServer::handle_send_complete,this,std::placeholders::_1));
    m_tcpserver.set_epoll_timeout_callback(std::bind(&EchoServer::handle_epoll_timeout,this,std::placeholders::_1));
}

EchoServer::~EchoServer()
{
}


void EchoServer::start()
{
    m_tcpserver.start();
}


void EchoServer::handle_on_message(ConnectionPtr conn, std::string& message)
{
    //LOG(INFO)<<"handle on message.";
    if(m_threadpool.size()==0)
        on_message(conn,message);
    else
        m_threadpool.add_task(std::bind(&EchoServer::on_message,this,conn,message));
}

//这些handler函数可写可不写，根据自己的需求来定。
void EchoServer::handle_new_connection(ConnectionPtr conn)
{
    LOG(INFO)<<"new connection(fd="<<conn->fd()<<",ip="<<conn->ip().c_str()<<",port="<<conn->port()<<") ok.";
}

void EchoServer::handle_close_connection(ConnectionPtr conn)
{
    LOG(INFO)<<"close connection(fd="<<conn->fd()<<",ip="<<conn->ip().c_str()<<",port="<<conn->port()<<") ok.";
}

void EchoServer::handle_error_connection(ConnectionPtr conn)
{
    LOG(INFO)<<"EchoServer conn error.";
}

void EchoServer::handle_send_complete(ConnectionPtr conn)
{
    //LOG(INFO)<<"Message send complete.";
}

void EchoServer::handle_epoll_timeout(EventLoop *loop)
{
    LOG(INFO)<<"EchoServer timeout.";
}

void EchoServer::on_message(ConnectionPtr conn, std::string& message)
{
    LOG(INFO)<<"message (eventfd="<<conn->fd()<<"):"<<message;
    //构建返回报文
    message = "reply:" + message;

    //将需要写的数据写入缓冲区，并注册写事件
    conn->send(message.data(), message.size());
}

void EchoServer::stop()
{
    m_threadpool.stop();
    LOG(INFO)<<"工作线程已停止。";
    m_tcpserver.stop();
}
